package com.dk.controller;

import com.dk.common.BaseVo;
import com.dk.common.GlobalVariable;
import com.dk.exception.SimpleException;
import com.dk.util.HttpLogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 上传文件用
 *
 * @author: A11181121050450
 * @date: 2020-05-18 15:30
 */
@Slf4j
@Controller
public class UploadFileController {

    @ResponseBody
    @PostMapping("uploadFile")
    public BaseVo uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile[] multipartFiles) {
        HttpLogUtil.printHeader(request);
        if (StringUtils.isEmpty(GlobalVariable.uploadFolderPath)) {
            throw new SimpleException("请选择文件夹");
        }
        Path source = Paths.get(GlobalVariable.uploadFolderPath);
        if (!source.toFile().exists()) {
            throw new SimpleException("文件夹不存在，请检查路径");
        }
        try {
            for (int i = 0; i < multipartFiles.length; i++) {
                MultipartFile multipartFile = multipartFiles[i];
                String originalFilename = multipartFile.getOriginalFilename();
                Path resolve = null;
                String prefix = null;
                String suffix = null;
                // 用来判断文件名是否重复，如果重复就在后面加（数字）
                for (int n = 1; ; n++) {
                    if (n > 999) {
                        throw new SimpleException("同名文件太多了");
                    }
                    resolve = source.resolve(originalFilename);
                    if (!resolve.toFile().exists()) {
                        break;
                    }
                    if (n == 1) {
                        int splitIndex = originalFilename.lastIndexOf(".");
                        prefix = splitIndex > 0 ? originalFilename.substring(0, splitIndex) : originalFilename;
                        suffix = splitIndex > 0 ? originalFilename.substring(splitIndex) : "";
                    }
                    originalFilename = prefix + " (" + n + ")" + suffix;
                }
                multipartFile.transferTo(resolve);
                GlobalVariable.uploadFilePath = resolve.toFile().getAbsolutePath();
                log.info("upload success:" + multipartFile.getName() + "->" + resolve.toFile().getAbsolutePath());
            }
        } catch (IOException e) {
            throw new SimpleException("文件上传失败", e);
        }
        return new BaseVo();
    }
}
